package com.ideal.manage.esms.service.diagnostic;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ideal.manage.esms.bean.diagnostic.DiagnoseManage;
import com.ideal.manage.esms.bean.diagnostic.DiagnoseResultInfo;
import com.ideal.manage.esms.bean.diagnostic.QDiagnoseResultInfo;
import com.ideal.manage.esms.jpa.JpaRepositoryImpl;
import com.ideal.manage.esms.service.ElasticsearchService;
import com.ideal.manage.esms.service.monitor.Utils;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import java.util.List;

@Service
@Transactional
public class DiagnoseService {
    private JpaRepositoryImpl<DiagnoseManage, String> diagnoseManageJpaRepository;
    @Autowired
    private EntityManager entityManager;
    @Autowired
    private ElasticsearchService elasticsearchService;

    @PostConstruct
    public void init() {
        this.diagnoseManageJpaRepository = new JpaRepositoryImpl<DiagnoseManage, String>(DiagnoseManage.class, entityManager);
    }

    public JSONObject getAsJsonObject(String id, String... names) {
        Long start = System.currentTimeMillis();
        QDiagnoseResultInfo qDiagnoseResultInfo = QDiagnoseResultInfo.diagnoseResultInfo;
        List<String> infoIds = diagnoseManageJpaRepository.query()
                .select(qDiagnoseResultInfo.id.max())
                .from(qDiagnoseResultInfo)
                .where(qDiagnoseResultInfo.equipment.id.eq(id)
                        .and(qDiagnoseResultInfo.setVal.in(names)))
                .groupBy(qDiagnoseResultInfo.setVal)
                .fetch();
        List<DiagnoseResultInfo> infos = diagnoseManageJpaRepository.query()
                .select(qDiagnoseResultInfo)
                .from(qDiagnoseResultInfo)
                .where(qDiagnoseResultInfo.id.in(infoIds))
                .fetch();
        JSONObject json = new JSONObject();
        for (String name : names) {
            //给一个默认值
            json.put(name, "暂无数据");
        }
        for (DiagnoseResultInfo info : infos) {
            json.put(info.getSetVal(), info.getResultVal());
        }
        System.out.println(System.currentTimeMillis() - start);
        return json;
    }


    /**
     * 获取总容量下面的各个信息
     *
     * @return
     */
    public JSONObject getZDLInfo(String id) {
        //单体容量变化量
        //最大允许充电电流
        //充电电流请求值
        //瞬态放电电流
        //瞬态充电电流
        //稳态放电电流
        //稳态充电电流
        return this.getAsJsonObject(id, "dtrlbhl", "zdyxcddl", "cddlqqz", "stfddl", "stcddl", "wtfddl", "wtcddl");
    }


    public JSONObject getBatteryInfo(String id) {
        return this.getAsJsonObject(id, /*容量*/"dtrlbzc", "dtrlfc", "dtrlqwz", "dtrlbyxs", "dtrlsfwsql",
                "dtrlsfwsqm", "dtrlsfwsqu", "dtrlsfwsc", "dtrlyzx",
                /*SOC*/ "dtsocbzc", "dtsocfc", "dtsocqwz",
                "dtsocbyxs", "dtsocsfwsql", "dtsocsfwsqm", "dtsocsfwsqu", "dtsocsfwsc", "dtsocyzx",
                /* DCIR*/ "dtzzbzc", "dtzzfc", "dtzzqwz", "dtzzbyxs", "dtzzsfwsql", "dtzzsfwsqm", "dtzzsfwsqu", "dtzzsfwsc", "dtzzyzx",
                /*电压*/"dtdybzc", "dtdyfc", "dtdyqwz", "dtdybyxs", "dtdysfwsql", "dtdysfwsqm", "dtdysfwsqu", "dtdysfwsc", "dtdyyzx",
                /*温度*/ "wdbzc", "wdfc", "wdqwz", "wdbyxs", "wdsfwsql", "wdsfwsqm", "wdsfwsqu", "wdsfwsc", "wdyzx");
    }

    public JSONObject getDiagnoseChangeValue(String id, String setVal) {
        JSONObject r = new JSONObject();
        r.put("value", 0);
        r.put("change_value", 0);
        QDiagnoseResultInfo qDiagnoseResultInfo = QDiagnoseResultInfo.diagnoseResultInfo;
        List<DiagnoseResultInfo> diagnoseResultInfos = diagnoseManageJpaRepository.query()
                .select(qDiagnoseResultInfo)
                .from(qDiagnoseResultInfo)
                .where(qDiagnoseResultInfo.equipment.id.eq(id)
                        .and(qDiagnoseResultInfo.setVal.eq(setVal)))
                .orderBy(qDiagnoseResultInfo.createTime.desc())
                .limit(2)
                .fetch();
        if (diagnoseResultInfos.isEmpty()) {
            return r;
        }
        if (diagnoseResultInfos.size() == 1) {
            r.put("value", diagnoseResultInfos.get(0).getResultVal());
        } else {
            r.put("value", diagnoseResultInfos.get(0).getResultVal());
            double t1 = Double.parseDouble(diagnoseResultInfos.get(0).getResultVal());
            double t2 = Double.parseDouble(diagnoseResultInfos.get(1).getResultVal());
            r.put("change_value", String.valueOf(t1 - t2));
        }
        return r;
    }

    public JSONObject getDiagnoseZdl(String id) {
        return this.getDiagnoseChangeValue(id, "kccdl");
    }

    public JSONObject getDiagnoseDcbrl(String id) {
        return this.getDiagnoseChangeValue(id, "dcbrl");
    }

    public JSONObject getDiagnoseXhcs(String id) {
        return this.getDiagnoseChangeValue(id, "xhcs");
    }

    public JSONObject getDiagnosePianCha(String id) {
        JSONObject r = new JSONObject();
        r.put("value", 0);
        r.put("change_value", 0);
        QDiagnoseResultInfo qDiagnoseResultInfo = QDiagnoseResultInfo.diagnoseResultInfo;
        List<DiagnoseResultInfo> socList = diagnoseManageJpaRepository.query()
                .select(qDiagnoseResultInfo)
                .from(qDiagnoseResultInfo)
                .where(qDiagnoseResultInfo.equipment.id.eq(id)
                        .and(qDiagnoseResultInfo.setVal.eq("soc")))
                .orderBy(qDiagnoseResultInfo.createTime.desc())
                .limit(2)
                .fetch();
        JSONArray batSocList = elasticsearchService.searchNewest(QueryBuilders.boolQuery()
                .filter(QueryBuilders.existsQuery("BatSoc")), 2);
        //补全数据
        DiagnoseResultInfo emptyResultInfo = new DiagnoseResultInfo();
        emptyResultInfo.setResultVal("0");
        JSONObject emptybatsoc = new JSONObject();
        emptybatsoc.put("BatSoc", 0);
        if (socList.isEmpty()) {
            socList.add(emptyResultInfo);
            socList.add(emptyResultInfo);
        }
        if (socList.size() == 1) {
            socList.add(emptyResultInfo);
        }
        if (batSocList.isEmpty()) {
            batSocList.add(emptybatsoc);
            batSocList.add(emptybatsoc);
        }
        if (batSocList.size() == 1) {
            batSocList.add(emptybatsoc);
        }
        //开始计算
        Double socT1 = Double.parseDouble(socList.get(0).getResultVal());
        Double socT2 = Double.parseDouble(socList.get(1).getResultVal());
        Double batSocT1 = batSocList.getJSONObject(0).getDoubleValue("BatSoc");
        Double batSocT2 = batSocList.getJSONObject(1).getDoubleValue("BatSoc");
        r.put("value", String.valueOf(Utils.halfUp(socT1 - batSocT1)));
        r.put("change_value", String.valueOf(Utils.halfUp(((socT1 - socT2) - (batSocT1 - batSocT2)))));
        return r;
    }

    public JSONObject getDiagnoseJiaoZheng(String id) {
        return this.getDiagnoseChangeValue(id, "soc");
    }
}
